﻿using Admin.NET.Application.Entity;
using Admin.NET.Application.Service.ProjectDailys.Dto;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.SemanticSemproxySearchResponse.Types;

namespace Admin.NET.Application.Service.ProjectDailys;
public class ProjectDailysService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Project> _project;
    private readonly UserManager _userManager;
    private readonly SqlSugarRepository<ProjectWorker> _ProjectWorker;
    private readonly SqlSugarRepository<ProjectDaily> _ProjectDaily;
    private readonly SqlSugarRepository<SysUser> _SysUser;

    private readonly SqlSugarRepository<ProjectDaily_Child> _ProjectDailyChild;


    public ProjectDailysService(SqlSugarRepository<Project> project,
                          SqlSugarRepository<ProjectWorker> ProjectWorker,
                          UserManager userManager,
                          SqlSugarRepository<SysUser> SysUser,
    SqlSugarRepository<ProjectDaily> ProjectDaily,
                          SqlSugarRepository<ProjectDaily_Child> ProjectDailyChild)
    {
        _project = project;
        _ProjectWorker = ProjectWorker;
        _SysUser = SysUser;
        _userManager = userManager;
        _ProjectDaily = ProjectDaily;
        _ProjectDailyChild = ProjectDailyChild;

    }


    [DisplayName("填写日志")]
    [ApiDescriptionSettings(Name = "AddProjectDaily"), HttpPost]
    public async Task<Boolean> AddProjectDaily(ProjectDaily Input)
    {
        if (Input.UseTime.IsNullOrEmpty())
        {
            Input.UseTime = 0;
            Input.Percent = 0;
        }
        //如果开始时间没有则显示当前时间
        if (Input.WorkStartTime.IsNullOrEmpty())
        {
            Input.WorkStartTime = DateTime.Now;
        }
        //如果进度为百分之百则为当前时间
        if (Input.Percent.Equals(100))
        {
            Input.WorkEndTime = DateTime.Now;
        }
        int countDaily =await  _ProjectDaily.CountAsync(p => p.CreateUserId.Equals(_userManager.UserId));
        Input.No = countDaily+1;
        //先加入大任务节点
        await _ProjectDaily.InsertAsync(Input);
        //如果加入大任务节点的时候进度不为0
        //if (!Input.Percent.Equals(0))
        //{
            ProjectDaily_Child projectDaily_Child = new ProjectDaily_Child();
            projectDaily_Child.ProjectDailyId = Input.Id;
            projectDaily_Child.WorkUse = Input.UseTime;
            projectDaily_Child.ToWrittenTime = Input.WorkStartTime;
            projectDaily_Child.DailyContent = Input.DailyContent;
            await _ProjectDailyChild.InsertAsync(projectDaily_Child);
        //}
        return true;
    }


    [DisplayName("更新日志")]
    [ApiDescriptionSettings(Name = "UpdateProjectDaily"), HttpPost]
    public async Task<Boolean> UpdateProjectDaily(UpdateProjectDailyInput Input)
    {
        ProjectDaily projectDaily = await _ProjectDaily.GetByIdAsync(Input.ProjectDailyId);

        //逻辑相反，先更新当天日志再去验证主日志
        Decimal? hasUseTime = 0;
        if (projectDaily.DailyContent!=null && !projectDaily.DailyContent.Equals(Input.DailyContent))
        {
            Input.Remark = "将任务《" + projectDaily.DailyContent + "》修改为" + "《" + Input.DailyContent + "》";
        }
        if (Input.Id.Equals(0)) {
            ProjectDaily_Child child = Input.Adapt<ProjectDaily_Child>();            
            child.ToWrittenTime = DateTime.Now;
            await _ProjectDailyChild.InsertAsync(child);
        }
        else
        {
            ProjectDaily_Child projectDaily_Child = await _ProjectDailyChild.GetByIdAsync(Input.Id);

            hasUseTime = projectDaily_Child.WorkUse;
            projectDaily_Child.Remark = Input.Remark;
            projectDaily_Child.DailyContent = Input.DailyContent;
            projectDaily_Child.WorkUse = Input.WorkUse;
            projectDaily_Child.Percent = Input.Percent;
            await _ProjectDailyChild.UpdateAsync(projectDaily_Child);
        }
        projectDaily.DailyContent = Input.DailyContent;
        projectDaily.Percent = Input.Percent;
        projectDaily.UseTime = projectDaily.UseTime - hasUseTime + Input.WorkUse;
        await _ProjectDaily.UpdateAsync(projectDaily);
        return true;
    }

    [DisplayName("废弃日志")]
    [ApiDescriptionSettings(Name = "AbondonProjectDaily"), HttpPost]
    public async Task<Boolean> AbondonProjectDaily(long Input)
    {
        ProjectDaily projectDaily = await _ProjectDaily.GetByIdAsync(Input);
        projectDaily.isAbondon = true;
        await _ProjectDaily.UpdateAsync(projectDaily);
        DateTime nextday = DateTime.Today.AddDays(1).ToDateTime();

        ProjectDaily_Child project_daily =await _ProjectDailyChild.AsQueryable().FirstAsync(p =>  p.ProjectDailyId.Equals(Input) && p.ToWrittenTime> DateTime.Today&& p.ToWrittenTime < nextday);
        if (project_daily.IsNullOrEmpty()) {
            ProjectDaily_Child projectDaily_Child = new ProjectDaily_Child();
            projectDaily_Child.ProjectDailyId = projectDaily.Id;
            projectDaily_Child.DailyContent = projectDaily.DailyContent;
            projectDaily_Child.WorkUse = 0;
            projectDaily_Child.ToWrittenTime = DateTime.Today;
            projectDaily_Child.Percent = projectDaily.Percent;
            projectDaily_Child.Remark =  "将任务《" + projectDaily.DailyContent + "》修改为" + "弃置阶段";
           await _ProjectDailyChild.InsertAsync(projectDaily_Child);
        }
        else
        {
            project_daily.Remark = project_daily.Remark + ",将任务《" + projectDaily.DailyContent + "》修改为" + "弃置阶段";
            await _ProjectDailyChild.UpdateAsync(project_daily);
        }
        return true;
    }

    [DisplayName("查询日志")]
    [ApiDescriptionSettings(Name = "GetProjectDaily"), HttpPost]
    public async Task<SqlSugarPagedList<ProjectDailyOutput>> GetProjectDaily(ProjectDailyPageInput Input)
    {
        DateTime dateTime;
        //如果是当天的
        if (Input.Date.Date.Equals(DateTime.Today)) {
            DateTime nextday = DateTime.Today.AddDays(1).ToDateTime();

            var Output = _ProjectDaily.AsQueryable()
            .Where(p => p.CreateUserId.Equals(_userManager.UserId)  && p.isAbondon == false)            
            .Where(p=>(p.WorkStartTime<DateTime.Today && p.Percent < 100) || (p.WorkStartTime>=DateTime.Today && p.WorkStartTime <nextday) || (p.UpdateTime >= DateTime.Today && p.Percent.Equals(100)))
            .Select(p=>new ProjectDailyOutput {
                ProjectId = p.ProjectId,
                ProjectDailyId = p.Id,
                WorkStartTime = p.WorkStartTime,
                Percent = p.Percent,
                DailyContent = p.DailyContent,
                No = (int)p.No,
                isAbondon = p.isAbondon
            })
            .ToPagedList(Input.Page, Input.PageSize);
            foreach (var item in Output.Items)
            {
                var elem = await _ProjectDailyChild
                    .AsQueryable().FirstAsync(p => p.ProjectDailyId.Equals(item.ProjectDailyId) && p.ToWrittenTime >= DateTime.Today);
                var projectInfo = await _project.AsQueryable().FirstAsync(p => p.Id == item.ProjectId);
                item.WorkStartTime = string.Format("{0:f}", item.WorkStartTime).ToDateTime();
                if (!projectInfo.IsNullOrEmpty())
                {
                    item.ProjectName = projectInfo.Name;
                }
                else
                {
                    item.ProjectName = "项目已删除";
                }
                if (elem.IsNullOrEmpty())
                {        
                    item.WorkUse = 0;
                }
                else
                {
                    item.Id= elem.Id;
                    item.DailyContent = elem.DailyContent;
                    item.WorkUse = elem.WorkUse;
                }
             }
            return Output;
        }
        else
        {
            DateTime nextday = Input.Date.AddDays(1).ToDateTime();
            var Output = _ProjectDailyChild.AsQueryable()
           .Where(p => p.CreateUserId.Equals(_userManager.UserId))
           .Where(p => p.ToWrittenTime >= Input.Date && p.ToWrittenTime < nextday)
           .Select(p => new ProjectDailyOutput
           {
               Id = p.Id,
               ProjectDailyId = p.ProjectDailyId,
               DailyContent = p.DailyContent,
               WorkUse = p.WorkUse,
               Percent = 0,
               No = 0,
               WorkStartTime = p.ToWrittenTime,
           })
           .ToPagedList(Input.Page, Input.PageSize);
            foreach (var item in Output.Items)
            {
                var elem = await _ProjectDaily.AsQueryable().FirstAsync(p => p.Id.Equals(item.ProjectDailyId));
                item.ProjectId = elem.ProjectId;
                var projectInfo = await _project.AsQueryable().FirstAsync(p => p.Id == item.ProjectId);
                item.isAbondon = elem.isAbondon;
                item.ProjectName = projectInfo.Name;
                item.No = (int)elem.No;
                item.WorkStartTime = string.Format("{0:f}", item.WorkStartTime).ToDateTime();
                item.WorkStartTime = elem.WorkStartTime;
                item.Percent = elem.Percent;
            }
            return Output;
        }

    }

    [DisplayName("获取日志统计")]
    [ApiDescriptionSettings(Name = "GetDailyTotal"), HttpPost]
    public async Task<List<ProjectDailyChildTotalOutput>> GetProjectDaily(DailyTotalInput Input)
    {
        List<SysUser> UsersList = await _SysUser.AsQueryable().Where(p=>p.SysOrg.Pid.Equals(1300000000104)).ToListAsync();
        List<ProjectDailyChildTotalOutput> Output = new List<ProjectDailyChildTotalOutput>();
        foreach (SysUser sysUser in UsersList)
        {
            ProjectDailyChildTotalOutput child = new ProjectDailyChildTotalOutput();
            child.Name = sysUser.RealName;
            child.Id = sysUser.Id;
          
            //周一的
            child.dayone = await GetProjectDetailChild(sysUser.Id, Input.startTime);
            child.daysecond = await GetProjectDetailChild(sysUser.Id, Input.startTime.AddDays(1));
            child.daythrid = await GetProjectDetailChild(sysUser.Id, Input.startTime.AddDays(2));
            child.dayforth = await GetProjectDetailChild(sysUser.Id, Input.startTime.AddDays(3));
            child.dayfith = await GetProjectDetailChild(sysUser.Id, Input.startTime.AddDays(4));
            child.daysixth = await GetProjectDetailChild(sysUser.Id, Input.startTime.AddDays(5));
            child.dayseventh = await GetProjectDetailChild(sysUser.Id, Input.startTime.AddDays(6));
            Output.Add(child);
        }
        return Output;
    }

    [DisplayName("获取今日日志统计")]
    [ApiDescriptionSettings(Name = "GetTodayProjectDaily"), HttpPost]
    public async Task<List<ProjectDailyChildTotalOutput>> GetTodayProjectDaily()
    {
        List<SysUser> UsersList = await _SysUser.AsQueryable().Where(p => p.SysOrg.Pid.Equals(1300000000104)).ToListAsync();

        List<ProjectDailyChildTotalOutput> Output = new List<ProjectDailyChildTotalOutput>();
        foreach (SysUser sysUser in UsersList)
        {
            ProjectDailyChildTotalOutput child = new ProjectDailyChildTotalOutput();
            child.Name = sysUser.RealName;
            child.Id = sysUser.Id;
            //周一的
            child.dayone = await GetProjectDetailChild(sysUser.Id, DateTime.Today);
            Output.Add(child);
        }
        return Output;
    }


    public async Task<List<ChildDetail>> GetProjectDetailChild(long id, DateTime dateTime)
    {
        List<ChildDetail> output = new List<ChildDetail>();
        var day = dateTime.ToDateTime();
        var nextday = dateTime.AddDays(1).ToDateTime();
        List<ProjectDaily_Child> childs = _ProjectDailyChild.AsQueryable().LeftJoin<ProjectDaily>((p, q) => p.ProjectDailyId.Equals(q.Id))
            .Where((p, q)=>!q.isAbondon.Equals(true))
            .Where((p,q) => p.CreateUserId.Equals(id))
            .Where((p, q) => p.WorkUse != 0)
            .Where((p, q) => p.ToWrittenTime >= day)
            .Where((p, q) => p.ToWrittenTime < nextday).Select((p,q)=>p).ToList();
        foreach (ProjectDaily_Child child in childs)
        {
            ChildDetail signal = new ChildDetail();
            signal.Id = child.Id;
            signal.Content = child.DailyContent;
            signal.Remarks = child.Remark;
            signal.Usetime = child.WorkUse;
            ProjectDaily projectDaily = await _ProjectDaily.AsQueryable().FirstAsync(p => p.Id.Equals(child.ProjectDailyId));
            if(projectDaily != null)
            {
                signal.Isstudy = projectDaily.IsStudy;
                Project projectinfo = await _project.AsQueryable().FirstAsync(p=>p.Id.Equals(projectDaily.ProjectId));
                if (projectinfo != null)
                {
                    signal.Project = projectinfo.Name+",任务进度"+projectDaily.Percent+"%";
                }
                else
                {
                    signal.Project = "无此项目名称" + ",任务进度" + projectDaily.Percent + "%";
                }
            }
            output.Add(signal);
        }
        return output;
    }
}
